<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Select, SelectOption, Spin } from 'ant-design-vue';

// import { VbenIcon } from '@vben/icons';
import { tagList } from '#/api/company/tag';
import { personalTagList } from '#/api/company/tag/personal';
import { ColorTag } from '#/components/dict';

import TagSelectModal from './tag-select-modal.vue';

const props = withDefaults(defineProps<Props>(), {
  tagType: undefined, // 1企业标签 2人员标签
});

const emit = defineEmits(['blur', 'change', 'close']);

interface Props {
  tagType?: number | string;
}

const modelValue = defineModel<(number | string)[]>('value', {
  default: () => [],
});

watch(
  () => modelValue.value,
  async () => {
    console.log('标签TreeSelect组件watch:', modelValue.value);
    await loadConfirmedOptions();
  },
);

const loading = ref(false);
const confirmedOptions = ref<any[]>([]);

const [BasicModal, modalApi] = useVbenModal({
  connectedComponent: TagSelectModal,
  onOpenChange: (isOpen) => {
    if (!isOpen) {
      emit('close');
    }
  },
});

// 筛选后确认
async function handleConfirm(data: any) {
  console.log('handleConfirm', data);
  modelValue.value = data.ids;
  confirmedOptions.value = data.options;
  emit('change', modelValue.value);
}

function onChange(value: any, selectedOption: any) {
  console.log('标签TreeSelect组件onChange:', value, selectedOption);
  confirmedOptions.value = confirmedOptions.value.filter((item) =>
    value.includes(item.value),
  );
  if (value.length === 0) {
    modelValue.value = [];
  }
  emit('change', modelValue.value);
}

// 点击标签搜索下拉框时触发，打开弹窗
function dropdownVisibleChange() {
  modalApi.setData({
    ids: modelValue.value,
    confirmedOptions: confirmedOptions.value,
  });
  modalApi.open();
}

onMounted(async () => {
  // console.log('onMOunted');
  console.log('标签TreeSelect组件初始化时默认值：', modelValue.value);
  await loadConfirmedOptions();
});

async function loadConfirmedOptions() {
  if (modelValue.value.length > 0) {
    loading.value = true;
    const tags =
      props.tagType === 1
        ? await tagList({ ids: modelValue.value })
        : await personalTagList({ ids: modelValue.value });
    console.log('查询标签结果：', tags);
    confirmedOptions.value = tags.map((item) => {
      return {
        label: item.name,
        value: item.id,
        groupName: item.groupName,
        status: item.status,
        listClass: item.listClass,
      };
    });
    loading.value = false;
  }
}
</script>
<template>
  <div class="flex w-full gap-1">
    <Spin :spinning="loading" class="flex-1">
      <Select
        v-model:value="modelValue"
        class="w-full"
        mode="multiple"
        placeholder="请选择"
        allow-clear
        :show-search="false"
        :show-arrow="true"
        max-tag-placeholder=""
        :open="false"
        @blur="emit('blur')"
        @change="onChange"
        @dropdown-visible-change="dropdownVisibleChange"
      >
        <template #maxTagPlaceholder="omittedValues">
          <span>+{{ omittedValues.length }}</span>
        </template>
        <SelectOption v-for="item in confirmedOptions" :key="item.value">
          <!--<span>{{ item.label }}</span>-->
          <ColorTag
            :color="item.listClass"
            :label="item.label"
            :disabled="item.status === '1'"
            :title="item.label"
          />
        </SelectOption>
      </Select>
    </Spin>
    <BasicModal :tag-type="tagType" @confirm="handleConfirm" :show-op="false" />
  </div>
</template>

<style lang="scss" scoped>
:deep(.ant-spin-nested-loading) {
  width: 100%;
}

:deep(.ant-select-selection-item) {
  padding-left: 0;
  border: none;
}
</style>
